package com.cande.loki.exercise.algorithm;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Description 测试下面那个tree类，检查自己能写出来不
 * @Author wgf
 * @Date 2025/10/18 8:38 PM
 */
public class TestTree {
    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        pre(node1);
        System.out.println("------");
        level(node1);
        System.out.println("build tree----------");
        Node root = new Node(1);
        Integer[] arr = {1,2,3,4,5};
        levelBuild(arr,root);
        level(root);
    }

    /**
     * 前序遍历
     * @param node
     */
    public static void pre(Node node) {
        if (node != null) {
            System.out.println(node.data);
            pre(node.left);
            pre(node.right);
        }
    }

    public static void levelBuild(Integer [] arr, Node node){
        Queue<Node> queue = new LinkedList<>();
        queue.offer(node);
        node.data = arr[0];

        int index = 1;

        while (!queue.isEmpty() && index < arr.length) {
            Node temp = queue.poll();

            if (index < arr.length && arr[index] != null) {
                temp.left = new Node(arr[index]);
                queue.offer(temp.left);
            }
            index++;

            if (index < arr.length && arr[index] != null) {
                temp.right = new Node(arr[index]);
                queue.offer(temp.right);
            }
            index++;

        }

    }

    public static void level(Node node){
        if (node == null) return;

        Queue<Node> queue = new LinkedList<>();
        queue.offer(node);

        while(!queue.isEmpty()){
            Node temp = queue.poll();

            System.out.println(temp.data);
            if (temp.left != null) {
                queue.offer(temp.left);
            }
            if (temp.right != null) {
                queue.offer(temp.right);
            }
        }
    }

    static class Node{
        int data ;
        Node left;
        Node right;

        public Node(int data) {
            this.data = data;
        }

        public int getData() {
            return data;
        }

        public void setData(int data) {
            this.data = data;
        }

        public Node getLeft() {
            return left;
        }

        public void setLeft(Node left) {
            this.left = left;
        }

        public Node getRight() {
            return right;
        }

        public void setRight(Node right) {
            this.right = right;
        }
    }
}
